package com.tanhua.server.service;

import com.itheima.commons.util.Constants;
import com.itheima.commons.util.JwtUtils;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.vo.CountsVo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.domain.User;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserService {
    @Autowired
    private SmsTemplate smsTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @DubboReference
    private UserApi userApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private FriendApi friendApi;

    @DubboReference
    private UserLikeApi userLikeApi;


    /**
     * 发送短信验证
     *
     * @param phone
     */
    public void sendCode(String phone) {
        //生成随机验证码
        //String code = RandomStringUtils.randomNumeric(6);
        //log.info("接收到的验证码为{}", code);
        //方便开发，所以将验证码写死
        String code = "123456";
        //调用阿里云服务发送短信
        // smsTemplate.sendSms(phone,code);
        //调用redis将验证码存入redis
        redisTemplate.opsForValue().set("CHECK_CODE_" + phone, code, Duration.ofMinutes(5));
    }

    /**
     * 校验验证码是否正确
     *
     * @param phone
     * @param verificationCode
     * @return
     */
    public Map loginVerification(String phone, String verificationCode) {
        //1.从redis中获取验证码
        String code = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2.校验验证码,正确后删除验证码
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        redisTemplate.delete("CHECK_CODE_" + phone);
        //3.判断用户是否注册
        boolean isNew = false;
        User user = userApi.findByMobile(phone);
        if (user == null) {
            //新用户
            user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            //注册环信用户
            String hxUser = "hx" + user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            //判断是否注册成功,更新用户信息
            if (create) {
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }

        }
        //3.登录成功，通过JWT生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id", user.getId());
        tokenMap.put("phone", phone);
        String token = JwtUtils.getToken(tokenMap);
        //4.构造数据响应
        Map retMap = new HashMap<>();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap;
    }

    /**
     * 校验修改手机号得短信是否正确
     */
    public boolean check(String phone, String verificationCode) {
        //1.从redis中获取验证码
        String code = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2.校验验证码,正确后删除验证码
        if (StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        redisTemplate.delete("CHECK_CODE_" + phone);
        return true;
    }

    /**
     * 修改手机号码
     *
     * @param phone
     */
    public void updatePhone(String phone) {
        //获取当前用户ID
        Long userId = UserHolder.getUserId();
        //调用API完成修改操作
        userApi.updatePhone(userId, phone);
    }

    /**
     * 查询互相喜欢数，查询粉丝数，查询喜欢数
     *
     * @return
     */
    public CountsVo counts() {
        //获得当前用户ID
        Long userId = UserHolder.getUserId();
        Integer loveCount = userLikeApi.findloveCount(userId);
        Integer fanCount = userLikeApi.findfanCount(userId);
        Integer eachLoveCount = friendApi.findEachLoveCount(userId);
        CountsVo vo = new CountsVo();
        vo.setFanCount(fanCount);
        vo.setLoveCount(loveCount);
        vo.setEachLoveCount(eachLoveCount);
        return vo;
    }
}
